package LeetCode;

import java.util.HashMap;
import java.util.Map;

public class Code105_buildTree {

    int pre_rootIndex = 0;
    Map<Integer, Integer> map = new HashMap<>();
    int[] preOrder;
    int[] inOrder;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        preOrder = preorder;
        inOrder = inorder;
        if (preOrder == null || inOrder == null){
            return null;
        }
        if (preOrder.length != inOrder.length){
            return null;
        }
        for (int i = 0; i < inorder.length; i++) {
            map.put(inOrder[i], i);
        }
        return dfs(0, inorder.length - 1);
    }

    private TreeNode dfs(int in_left, int in_right) {
        if (in_left > in_right){
            return null;
        }
        int root_val = preOrder[pre_rootIndex];
        TreeNode root = new TreeNode(root_val);
        int in_rootIndex = map.get(root_val);
        pre_rootIndex++;
        root.left = dfs(in_left, in_rootIndex - 1);
        root.right = dfs(in_rootIndex + 1, in_right);
        return root;
    }
}
